<template>
  <div class="clearfix">
    <!-- :action="uploadImgUrl"  :data="dataObj" -->
    <a-upload
      v-model:file-list="fileList"
     
      :accept="fileType.join(',')"
      list-type="picture-card"
      
      @preview="handlePreview"
      :beforeUpload="handleBeforeUpload"
      :max-count="limit"
      :customRequest="customRequest"
      @remove="handleDelete"
      @change="handleChange"
    >
      <div v-if="fileList.length < limit">
        <plus-outlined />
        <div style="margin-top: 8px">上传</div>
      </div>
    </a-upload>
    <div
      class="el-upload__tip"
      v-if="isShowTip"
    >
      请上传
      <template v-if="fileSize">
        大小不超过
        <b style="color: #f56c6c">{{ fileSize }}MB</b>
      </template>
      <template v-if="fileType">
        格式为
        <b style="color: #f56c6c">{{ fileType.join('/') }}</b>
      </template>
      的文件
      <template v-if="limit">
        ，最多上传
        <b style="color: #f56c6c">{{ limit }}</b>
        张
      </template>
    </div>
    <a-modal
      :open="previewVisible"
      :title="previewTitle"
      :footer="null"
      @cancel="handleCancel"
    >
      <img
        alt="example"
        style="width: 100%"
        :src="previewImage"
      />
    </a-modal>
  </div>
</template>
<script setup>
 import OSS from 'ali-oss'
// import * as OSS from "@/utils/oss.js";
  import config from '@/config/index.js'
  import * as qiniu from 'qiniu-js'
  import { getUpdateToken,upload_ali,uploadSysToken } from '@/api/index'
  import { PlusOutlined } from '@ant-design/icons-vue'
  import { getToken } from '@/utils/auth'
  import { ref, defineProps, watch, defineEmits, reactive } from 'vue'
  import { message, Upload } from 'ant-design-vue'
  import { reject } from 'lodash-es'
  const props = defineProps({
    modelValue: [String, Object, Array],
    // 图片数量限制
    limit: {
      type: Number,
      default: 5
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ['png', 'jpg', 'jpeg', 'webp']
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    }
  })
  const uploadList = ref([])
  const dataObj = reactive({ token: null, key: '' })
  const previewVisible = ref(false)
  const previewImage = ref('')
  const previewTitle = ref('')
  const number = ref(0)
  const fileList = ref([])
  const emit = defineEmits()
  const baseUrl = ref('')
  const qiUrl = ref(config.upLoadUrl)
  const uploadImgUrl = ref(config.qiniuUrl)
  const getTokens = () => {
    // return new Promise((resolve, reject) => {
    //   getUpdateToken({}).then((res) => {
    //     dataObj.token = res.data.qiniu_token
    //     resolve(true)
    //   })
    // }).catch((err) => {
    //   reject(false) .
    // })
  }
const customRequest=(file)=>{
  
  const dir = "cells-admin/";
  const fileName = `${dir}-${file.file.name}`; //定义唯一的文件名
  const formData = new FormData();
  formData.append("file", file.file);
  // formData.append("fileName", fileName);
  // upload_ali(formData).then((res) => {

  //   uploadList.value.push({
  //       name: file.file.name,
  //       url: res.data.url
  //     })
  //     file.onSuccess(res, file);
  //     uploadedSuccessfully()
  // }).catch((err) => {})
  // const dir = "cell-admin/";
  // const fileName = `${dir}-${file.file.name}`; //定义唯一的文件名
  
  uploadSysToken({}).then(res1=>{
    let oss=new OSS({...res1.stsToken})
    var fileFormat = (file.file.name).split(".");
       
    let name=Date.now() + "." + fileFormat[fileFormat.length - 1]

    
    oss.put(res1.filename+name, file.file)
    .then((res) => {
      console.log("上传成功", res);
      uploadList.value.push({
        name: fileName,
        url: res.url
      })

      uploadedSuccessfully()
    })
    .catch((error)=>{
      console.log('发生错误', error);
    })



  })

  

}
  const headers = ref({ Authorization: '6b18855af89746ddb6642ff7b261e589' }) //+ getToken()
  // 上传前loading加载
  const handleBeforeUpload = async (file) => {
    // let res = await getTokens()
    // if (res) {
 
      dataObj.key = new Date().getTime()+file.name
      let isImg = false
      if (props.fileType.length) {
        let fileExtension = ''
        if (file.name.lastIndexOf('.') > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)
        }
        isImg = props.fileType.some((type) => {
          if (file.type.indexOf(type) > -1) return true
          if (fileExtension && fileExtension.indexOf(type) > -1) return true
          return false
        })
      } else {
        isImg = file.type.indexOf('image') > -1
      }

      if (!isImg) {
        message.error(`文件格式不正确, 请上传${props.fileType.join('/')}图片格式文件!`)
        return false
      }
      if (props.fileSize) {
        const isLt = file.size / 1024 / 1024 < props.fileSize
        if (!isLt) {
          message.error(`上传头像图片大小不能超过 ${props.fileSize} MB!`)
          return false
        }
      }
      // message.loading('正在上传图片，请稍候...', 2.5).then(
      //   () => message.success('上传完成', 2.5),
      //   // eslint-disable-next-line @typescript-eslint/no-empty-function
      //   () => {}
      // )

      number.value++

      return true
    // }
  }
  function handleDelete(file) {
    const findex = fileList.value.map((f) => f.name).indexOf(file.name)
 let url=fileList.value[findex].url
 
    uploadSysToken({}).then(res1=>{
      let oss=new OSS({...res1.stsToken})
      let newUrl=url.split(res1.stsToken.endpoint+'/')[1]
     
      oss.delete(newUrl).then(res=>{})
    })
    if (findex > -1 && uploadList.value.length === number.value) {
      fileList.value.splice(findex, 1)
     
      emit('update:modelValue', listToString(fileList.value))
      return false
    }
  }
  watch(
    () => props.modelValue,
    (val) => {
      if (val) {
        // 首先将值转为数组
        const list = Array.isArray(val) ? val : props.modelValue.split(',')
        // 然后将数组转为对象数组
        fileList.value = list.map((item) => {
          if (typeof item === 'string') {
            if (item.indexOf(baseUrl.value) === -1) {
              item = { name: baseUrl.value + item, url: baseUrl.value + item }
            } else {
              item = { name: item, url: item }
            }
          }
          return item
        })
      } else {
        fileList.value = []
        return []
      }
    },
    { deep: true, immediate: true }
  )
  const handleChange = ({ file, fileList, event }) => {
    // debugger
    // if (file.status === 'done' && file.response.key) {
    //   uploadList.value.push({
    //     name: file.response.key,
    //     url: qiUrl.value + file.response.key
    //   })

    //   uploadedSuccessfully()
    // }
    if (file.status === 'error' || file.status === 'removed') {
      number.value--

      // message.error(res.msg)
      proxy.$refs.imageUpload.handleRemove(file)
      uploadedSuccessfully()
    }
  }
  // 上传结束处理
  function uploadedSuccessfully() {
     
    if (number.value > 0 && uploadList.value.length === number.value) {
      fileList.value = fileList.value.filter((f) => f.url !== undefined).concat(uploadList.value)
      uploadList.value = []
      number.value = 0
      emit('update:modelValue', listToString(fileList.value))
      // proxy.$modal.closeLoading()
    }
  }
  // 上传失败
  function handleUploadError() {
    message.error('上传图片失败')
    // proxy.$modal.closeLoading()
  }
  function getBase64(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => resolve(reader.result)
      reader.onerror = (error) => reject(error)
    })
  }

  const handleCancel = () => {
    previewVisible.value = false
    previewTitle.value = ''
  }
  const handlePreview = async (file) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj)
    }
    previewImage.value = file.url || file.preview
    previewVisible.value = true
    previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1)
  }
  // 对象转成指定字符串分隔
  function listToString(list, separator) {
    let strs = ''
    separator = separator || ','
    for (let i in list) {
      if (undefined !== list[i].url && list[i].url.indexOf('blob:') !== 0) {
        strs += list[i].url.replace(baseUrl, '') + separator
      }
    }

    return strs != '' ? strs.substr(0, strs.length - 1) : ''
  }
</script>
<style scoped>
  /* you can make up upload button and sample style by using stylesheets */
  .ant-upload-select-picture-card i {
    font-size: 32px;
    color: #999;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }
</style>
